package com.paul.redis.config;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.interceptor.KeyGenerator;

import java.lang.reflect.Method;

/**
 * @author ：zmk
 * @date ：Created in 2021/11/15 16:12
 * @description：自定义Redis Key,解决springboot cache redis(策略：DefaultKeyGenerator，SimpleKeyGenerator )
 *      在某种(缓存键值当参数列表的值相同时是一样的 这样就会造成获取到错误的缓存数据)情况下出现数据错误
 */
public class MyKeyGenerator implements KeyGenerator {
    private static final Logger logger = LoggerFactory.getLogger(MyKeyGenerator.class);

    @Override
    public Object generate(Object target, Method method, Object... params) {
        StringBuilder sb = new StringBuilder();
        sb.append(target.getClass().getName());
        sb.append("&");
        sb.append(method.getName());
        sb.append("&");
        for (Object obj : params) {
            if (obj != null) {
                sb.append(obj.getClass().getName());
                sb.append("&");
                sb.append(JSON.toJSONString(obj));
                sb.append("&");
            }
        }
        logger.info("redis cache key str: " + sb.toString());

        logger.info("redis cache key sha256Hex: " + DigestUtils.sha256Hex(sb.toString()));
        return DigestUtils.sha256Hex(sb.toString());

    }
}
